<?php
/**
 * Created by PhpStorm.
 * User: chen
 * Date: 2019/1/17
 * Time: 20:44
 */

namespace App\Services;

use App\Models\Topic;
use App\Models\TranslateRecord;
use App\Models\TranslateSection;
use Illuminate\Support\Facades\DB;
use Phphub\Markdown\Markdown;

class TranslateService
{
    protected $markdownHandle;

    public function __construct(Markdown $markdown)
    {
        $this->markdownHandle = $markdown;
    }

    /**
     * 创建原文
     * @param $title
     * @param $originalUrl
     * @param $bodyOriginal
     */
    public function create($data)
    {
        DB::transaction(function () use ($data)
        {
            $topic = Topic::create($this->getTopicData($data));

            $translateSections = $this->splitTranslateToSections($data['body_original']);

            foreach ($translateSections as $section)
            {
                $topic->translateSections()->create($this->getSectionData($section));
            }
        });
    }

    /**
     * 原文更新
     * @param $topic_id
     * @param $title
     * @param $originalUrl
     * @param $bodyOriginal
     */
    public function update($topic_id, $data)
    {
        DB::transaction(function () use ($topic_id, $data)
        {
            Topic::where('id', $topic_id)
                  ->update($this->getTopicData($data));

            $topic = Topic::where('id', $topic_id)->firstOrFail();
            //修改后的section
            $translateSections_new = $this->splitTranslateToSections($data['body_original']);
            //旧的section
            $translateSections_old = $topic->translateSections()->orderBy('id', 'asc')->get();

            //新section数目大于原section数目
            if(count($translateSections_new) > count($translateSections_old))
            {
                foreach ($translateSections_new as $key => $section)
                {
                    //按顺序更新
                    if(isset($translateSections_old[$key]))
                    {
                        $translateSections_old[$key]->update($this->getSectionData($section));
                    }
                    else
                    {
                        $topic->translateSections()->create($this->getSectionData($section));
                    }
                }

            }
            //原section数目大于新section数目
            elseif(count($translateSections_new) <= count($translateSections_old))
            {
                $i = 0;
                foreach ($translateSections_new as $key => $section)
                {
                    //按顺序更新
                    $translateSections_old[$key]->update($this->getSectionData($section));
                    $i = $key;
                }
                //
                $old_sec_count = count($translateSections_old);
                $i = $i + 1;
                for (; $i < $old_sec_count; $i++)
                {
                    $translateSections_old[$i]->delete();
                }
            }

        });
    }

    protected function getSectionData($translateSection)
    {
        return [
            'original_text' => $translateSection,
            'original_text_html' => $this->markdownHandle->convertMarkdownToHtml($translateSection),
        ];
    }

    protected function getTopicData($data)
    {
        //$data['title'], $data['original_url'], $data['body_original']

        $bodyOriginal = str_replace('</translate>', '', $data['body_original']);
        $data['body'] = $this->markdownHandle->convertMarkdownToHtml($bodyOriginal);
        $data['user_id'] = \Auth()->id();
        $data['translate_status'] = Topic::NOT_TRANSLATED;
        $data['category_id'] = config('phphub.translate_id');
        return $data;
    }

    protected function splitTranslateToSections($translate)
    {
        return explode('</translate>', $translate);
    }


    //*****************用户翻译********************//
    /**
     * @param $topic_id
     * @return mixed
     */
    public function getTranslatedSections($topic_id)
    {
        return TranslateSection::where('topic_id', $topic_id)
                    ->where('is_translated', TranslateSection::IS_TRANSLATED)
                    ->orderBy('id', 'ASC')
                    ->get();
    }

    /**
     * @param $topic_id
     * @return mixed
     */
    public function getUnTranslatedSections($topic_id)
    {
        return TranslateSection::where('topic_id', $topic_id)
            ->where('is_translated', TranslateSection::NOT_TRANSLATED)
            ->orderBy('id', 'ASC')
            ->get();
    }

    /**
     * @param $topic_id
     * @return mixed
     */
    public function unTranslatedCount($topic_id)
    {
        return TranslateSection::where('topic_id', $topic_id)
            ->where('is_translated', TranslateSection::NOT_TRANSLATED)
            ->count();
    }

    public function updateTopicData($topic_id, $translate_status,$body_original)
    {
        $topic_data = ['translate_status' => $translate_status,
                        'body_original' => $body_original,
                        'body' => $this->markdownHandle->convertMarkdownToHtml($body_original)];

        Topic::where('id',$topic_id)->update($topic_data);

    }

    public function updateSectionData($section_id, $translate_text, $section_data)
    {
        $section_data['translate_text_html'] = $this->markdownHandle->convertMarkdownToHtml($translate_text);
        TranslateSection::where('id', $section_id)->update($section_data);
    }

    public function updateRecordData($record_id, $record_data)
    {
        TranslateRecord::where('id', $record_id)->update($record_data);
    }

}